<template>
  <van-button
    v-if="isFollowed"
    round
    size="small"
    :loading="loading"
    @click="onFollow"
  >已关注</van-button>
  <van-button
    v-else
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
    :loading="loading"
    @click="onFollow"
  >关注</van-button>
</template>

<script>
import { addFollow, delFollow } from '@/api/user'
import { mapState } from 'vuex'
export default {
  name: 'FollowUser',
  props: {
    isFollowed: {
      type: Boolean,
      required: true
    },
    userId: {
      type: [String, Object, Number],
      required: true
    }
  },
  computed: {
    ...mapState(['user'])
  },
  data () {
    return {
      loading: false
    }
  },
  methods: {
    // 点击关注和取消关注
    async onFollow() {
      if (!this.user) return this.$toast('请先登录！')
      this.loading = true
      try {
        if (this.isFollowed) {
          // true 已关注 点击取消关注
          await delFollow(this.userId)
          this.$toast('取消关注成功!')
          // this.articles.is_followed = false
        } else {
          // false 未关注  点击添加关注
          await addFollow(this.userId)
          this.$toast('关注成功!')
          // this.articles.is_followed = true
        }
        this.$emit('updateFollow', !this.isFollowed)
      } catch (error) {
        console.log(error)
        let message = '操作失败,请稍后重试!'
        if (error.response && error.response.status === 400) {
          message = '你不能关注你自己'
        } else if (error.response && error.response.status === 401) {
          message = '账号未登录！'
        } else if (error.response && error.response.status === 507) {
          message = '服务器内部错误！'
        }
        this.$toast(message)
      }
      this.loading = false
    }
  }
}
</script>

<style scoped lang="less"></style>
